package org.ysu.shoeShopping.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.ysu.shoeShopping.service.ShoesService;
import org.ysu.shoeShopping.service.TypesService;
import org.ysu.shoeShopping.service.ColorService;
import org.ysu.shoeShopping.service.BrandsService;
import org.ysu.shoeShopping.service.ShoesizesService;
import org.ysu.shoeShopping.service.SizesService;
import org.ysu.shoeShopping.entity.Shoes;
import org.ysu.shoeShopping.entity.Types;
import org.ysu.shoeShopping.entity.Color;
import org.ysu.shoeShopping.entity.Brands;
import org.ysu.shoeShopping.entity.Shoesizes;
import org.ysu.shoeShopping.entity.Sizes;
import org.ysu.shoeShopping.tools.Result;

import javax.annotation.Resource;
import java.util.*;

/**
 * 产品相关API控制器
 * 处理前端产品展示需求
 */
@RestController
@RequestMapping("product")
@CrossOrigin(origins = "*")
public class ShoesController {

    @Autowired
    private ShoesService shoesService;

    @Resource
    private TypesService typesService;

    @Resource
    private ColorService colorService;

    @Resource
    private BrandsService brandsService;

    @Resource
    private ShoesizesService shoesizesService;

    @Resource
    private SizesService sizesService;

    /**
     * 获取热门商品
     * 前端请求路径: /product/hotProducts
     *
     * @return 热门商品列表
     */
    @GetMapping("/hotProducts")
    public ResponseEntity<Map<String, Object>> getHotProducts() {
        try {
            // 获取销量最高的鞋子商品，按销量排序，取前8个
            List<Shoes> topShoes = shoesService.getTopSellingShoes(8);

            List<Map<String, Object>> hotProducts = new ArrayList<>();

            for (Shoes shoe : topShoes) {
                Map<String, Object> product = new HashMap<>();
                product.put("id", shoe.getSid());
                product.put("name", shoe.getSname());
                product.put("description", shoe.getSinfo() != null && !shoe.getSinfo().trim().isEmpty()
                        ? shoe.getSinfo() : "时尚优质鞋履，品质保证");
                product.put("price", shoe.getSdiscount() != null ? shoe.getSdiscount().intValue() : shoe.getSprices().intValue());
                product.put("originalPrice", shoe.getSprices().intValue());
                product.put("rating", generateRating(shoe.getStimessold())); // 基于销量生成评分
                product.put("sales", shoe.getStimessold());

                // 处理图片，取第一张图片
                String imageUrl = "/api/placeholder/200/200"; // 默认图片
                if (shoe.getSimage() != null && !shoe.getSimage().trim().isEmpty()) {
                    String[] images = shoe.getSimage().split(";");
                    if (images.length > 0 && !images[0].trim().isEmpty()) {
                        imageUrl = "/api/images/" + images[0].trim();
                    }
                }
                product.put("image", imageUrl);

                hotProducts.add(product);
            }

            // 构建标准响应格式
            Map<String, Object> response = new HashMap<>();
            response.put("data", hotProducts);
            response.put("status", 200);
            response.put("message", "success");

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            // 错误处理
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("data", new ArrayList<>());
            errorResponse.put("status", 500);
            errorResponse.put("message", "服务器内部错误");
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 获取最新商品
     * 前端请求路径: /api/product/newProducts
     *
     * @return 最新商品列表
     */
    @GetMapping("/newProducts")
    public ResponseEntity<Map<String, Object>> getNewProducts() {
        try {
            // 获取最新发布的4双鞋子商品，按发布时间排序
            List<Shoes> newShoes = shoesService.getLatestShoes(8);

            List<Map<String, Object>> newProducts = new ArrayList<>();

            for (Shoes shoe : newShoes) {
                Map<String, Object> product = new HashMap<>();
                product.put("id", shoe.getSid());
                product.put("name", shoe.getSname());
                product.put("description", shoe.getSinfo() != null && !shoe.getSinfo().trim().isEmpty()
                        ? shoe.getSinfo() : "全新上市，品质保证");
                product.put("price", shoe.getSprices().intValue()); // 原价
                product.put("currentPrice", shoe.getSdiscount() != null ? shoe.getSdiscount().intValue() : shoe.getSprices().intValue()); // 现价
                product.put("sales", shoe.getStimessold() != null ? shoe.getStimessold() : 0);

                // 处理图片，取第一张图片
                String imageUrl = "/api/placeholder/200/200"; // 默认图片
                if (shoe.getSimage() != null && !shoe.getSimage().trim().isEmpty()) {
                    String[] images = shoe.getSimage().split(";");
                    if (images.length > 0 && !images[0].trim().isEmpty()) {
                        imageUrl = "/api/images/" + images[0].trim();
                    }
                }
                product.put("image", imageUrl);

                newProducts.add(product);
            }

            // 构建标准响应格式
            Map<String, Object> response = new HashMap<>();
            response.put("data", newProducts);
            response.put("status", 200);
            response.put("message", "success");

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            // 错误处理
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("data", new ArrayList<>());
            errorResponse.put("status", 500);
            errorResponse.put("message", "服务器内部错误");
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 获取鞋类种类
     * 前端请求路径: /product/categories
     *
     * @return 鞋类种类列表
     */
    @GetMapping("/categories")
    public ResponseEntity<Map<String, Object>> getCategories() {
        try {
            // 获取所有启用的鞋类型
            List<Types> allTypes = typesService.getAllActiveTypes();

            List<Map<String, Object>> categories = new ArrayList<>();

            for (Types type : allTypes) {
                Map<String, Object> category = new HashMap<>();
                category.put("id", type.getTid());
                category.put("name", type.getTname());
                category.put("mark",type.getTremarks());
                category.put("icon", ""); // 图标字段，暂时为空

                categories.add(category);
            }

            // 构建标准响应格式
            Map<String, Object> response = new HashMap<>();
            response.put("data", categories);
            response.put("status", 200);
            response.put("message", "success");

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            // 错误处理
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("data", new ArrayList<>());
            errorResponse.put("status", 500);
            errorResponse.put("message", "服务器内部错误");
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 根据ID查询商品详情
     * 前端请求路径: /product/detail/{id}
     *
     * @param productId 商品ID
     * @return 商品详情信息
     */
    @GetMapping("/detail/{id}")
    public Result<Map<String, Object>> getProductDetail(@PathVariable("id") Integer productId) {
        try {
            // 根据ID查询商品信息
            Shoes shoe = shoesService.queryById(productId);

            if (shoe == null) {
                return Result.fail("404", "商品不存在");
            }

            // 查询颜色信息
            String colorName = "";
            if (shoe.getScid() != null) {
                Color color = colorService.queryById(shoe.getScid());
                if (color != null) {
                    colorName = color.getCname();
                }
            }

            // 查询分类信息
            String categoryName = "";
            Integer categoryId = shoe.getTypeId();
            if (categoryId != null) {
                Types type = typesService.queryById(categoryId);
                if (type != null) {
                    categoryName = type.getTname();
                }
            }

            // 构建商品详情对象
            Map<String, Object> product = new HashMap<>();
            product.put("id", shoe.getSid());
            product.put("productCode", shoe.getSnum() != null ? shoe.getSnum() : "");
            product.put("name", shoe.getSname() != null ? shoe.getSname() : "");
            product.put("price", shoe.getSdiscount() != null ? shoe.getSdiscount().doubleValue() :
                       (shoe.getSprices() != null ? shoe.getSprices().doubleValue() : 0.0));
            product.put("sold", shoe.getStimessold() != null ? shoe.getStimessold() : 0);
            product.put("description", shoe.getSinfo() != null ? shoe.getSinfo() : "");
            product.put("categoryId", categoryId != null ? categoryId.toString() : "");
            product.put("categoryName", categoryName);
            product.put("originalPrice", shoe.getSprices() != null ? shoe.getSprices().doubleValue() : 0.0);
            product.put("color", colorName);
            // 添加内容简介字段（详细描述信息）
            product.put("summary", shoe.getSdetail() != null ? shoe.getSdetail() : "");
            // 添加单价鞋总积分字段
            product.put("totalIntegral", shoe.getSintegral() != null ? shoe.getSintegral().doubleValue() : 0.0);

            return Result.success(product);
        } catch (Exception e) {
            return Result.fail("500", "查询商品详情失败: " + e.getMessage());
        }
    }

    /**
     * 商品搜索接口
     * 前端请求路径: /product/search
     * 支持按名称、性别、类型等条件搜索商品
     *
     * @param keyword 搜索关键词（可选）
     * @param gender 性别筛选（可选）：男、女、通用
     * @param typeId 商品类型ID（可选）
     * @param brandId 品牌ID（可选）
     * @param minPrice 最低价格（可选）
     * @param maxPrice 最高价格（可选）
     * @param page 页码（默认1）
     * @param size 每页大小（默认20）
     * @return 搜索结果列表
     */
    @GetMapping("/search")
    public ResponseEntity<Map<String, Object>> searchProducts(
            @RequestParam(value = "keyword", required = false) String keyword,
            @RequestParam(value = "gender", required = false) String gender,
            @RequestParam(value = "typeId", required = false) Integer typeId,
            @RequestParam(value = "brandId", required = false) Integer brandId,
            @RequestParam(value = "minPrice", required = false) Float minPrice,
            @RequestParam(value = "maxPrice", required = false) Float maxPrice,
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "size", defaultValue = "20") int size) {
        try {
            // 调用Service层搜索商品
            List<Shoes> searchResults = shoesService.searchShoes(keyword, gender, typeId, brandId, minPrice, maxPrice, page, size);

            List<Map<String, Object>> products = new ArrayList<>();

            for (Shoes shoe : searchResults) {
                Map<String, Object> product = new HashMap<>();
                product.put("id", shoe.getSid());
                product.put("name", shoe.getSname());
                product.put("description", shoe.getSinfo() != null && !shoe.getSinfo().trim().isEmpty()
                        ? shoe.getSinfo() : "品质保证，时尚首选");

                // 添加性别信息
                product.put("gender", shoe.getSgender() != null ? shoe.getSgender() : "通用");

                // 添加原价和现价
                product.put("originalPrice", shoe.getSprices() != null ? shoe.getSprices().doubleValue() : 0.0);
                product.put("currentPrice", shoe.getSdiscount() != null ? shoe.getSdiscount().doubleValue() :
                           (shoe.getSprices() != null ? shoe.getSprices().doubleValue() : 0.0));

                // 为了兼容前端，保留price字段
                product.put("price", shoe.getSdiscount() != null ? shoe.getSdiscount().doubleValue() :
                           (shoe.getSprices() != null ? shoe.getSprices().doubleValue() : 0.0));

                product.put("sales", shoe.getStimessold() != null ? shoe.getStimessold() : 0);
                product.put("rating", generateRating(shoe.getStimessold()));

                // 添加商品编号
                product.put("productCode", shoe.getSnum() != null ? shoe.getSnum() : "");

                // 添加品牌和类型ID
                product.put("brandId", shoe.getBrandId());
                product.put("typeId", shoe.getTypeId());

                // 添加颜色信息
                String colorName = "";
                if (shoe.getScid() != null) {
                    Color color = colorService.queryById(shoe.getScid());
                    if (color != null) {
                        colorName = color.getCname();
                    }
                }
                product.put("color", colorName);
                product.put("colorId", shoe.getScid());

                // 添加品牌信息
                String brandName = "";
                if (shoe.getBrandId() != null) {
                    Brands brand = brandsService.queryById(shoe.getBrandId());
                    if (brand != null) {
                        brandName = brand.getBname();
                    }
                }
                product.put("brand", brandName);

                // 添加尺码信息
                List<String> availableSizes = new ArrayList<>();
                try {
                    List<Shoesizes> shoeSizeList = shoesizesService.findByShoeId(shoe.getSid());
                    for (Shoesizes shoeSize : shoeSizeList) {
                        if (shoeSize.getSizeId() != null) {
                            Sizes sizeInfo = sizesService.queryById(shoeSize.getSizeId());
                            if (sizeInfo != null && shoeSize.getScount() != null && shoeSize.getScount() > 0) {
                                availableSizes.add(sizeInfo.getSizenum().toString());
                            }
                        }
                    }
                } catch (Exception e) {
                    // 如果查询尺码失败，返回空列表
                }
                product.put("sizes", availableSizes);

                // 处理图片，取第一张图片
                String imageUrl = "/api/placeholder/200/200"; // 默认图片
                if (shoe.getSimage() != null && !shoe.getSimage().trim().isEmpty()) {
                    String[] images = shoe.getSimage().split(";");
                    if (images.length > 0 && !images[0].trim().isEmpty()) {
                        imageUrl = "/api/images/" + images[0].trim();
                    }
                }
                product.put("image", imageUrl);

                products.add(product);
            }

            // 构建标准响应格式
            Map<String, Object> response = new HashMap<>();
            response.put("data", products);
            response.put("status", 200);
            response.put("message", "success");
            response.put("total", products.size()); // 当前页商品数量
            response.put("page", page);
            response.put("size", size);

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            // 错误处理
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("data", new ArrayList<>());
            errorResponse.put("status", 500);
            errorResponse.put("message", "搜索失败: " + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 获取品牌列表
     * 前端请求路径: /product/brands
     *
     * @return 品牌列表
     */
    @GetMapping("/brands")
    public ResponseEntity<Map<String, Object>> getBrands() {
        try {
            // 获取所有启用的品牌
            List<Brands> allBrands = brandsService.getAllActiveBrands();

            List<Map<String, Object>> brands = new ArrayList<>();

            for (Brands brand : allBrands) {
                Map<String, Object> brandMap = new HashMap<>();
                brandMap.put("id", brand.getBid());
                brandMap.put("name", brand.getBname());
                brandMap.put("gender", brand.getBsex() != null ? brand.getBsex() : "");
                brandMap.put("remarks", brand.getBremarks() != null ? brand.getBremarks() : "");

                brands.add(brandMap);
            }

            // 构建标准响应格式
            Map<String, Object> response = new HashMap<>();
            response.put("data", brands);
            response.put("status", 200);
            response.put("message", "success");

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            // 错误处理
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("data", new ArrayList<>());
            errorResponse.put("status", 500);
            errorResponse.put("message", "获取品牌列表失败: " + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 根据ID获取品牌详情
     * 前端请求路径: /product/brands/{id}
     *
     * @param brandId 品牌ID
     * @return 品牌详情
     */
    @GetMapping("/brands/{id}")
    public Result<Map<String, Object>> getBrandDetail(@PathVariable("id") Integer brandId) {
        try {
            Brands brand = brandsService.queryById(brandId);

            if (brand == null) {
                return Result.fail("404", "品牌不存在");
            }

            Map<String, Object> brandDetail = new HashMap<>();
            brandDetail.put("id", brand.getBid());
            brandDetail.put("name", brand.getBname());
            brandDetail.put("gender", brand.getBsex() != null ? brand.getBsex() : "");
            brandDetail.put("state", brand.getBstate());
            brandDetail.put("remarks", brand.getBremarks() != null ? brand.getBremarks() : "");

            return Result.success(brandDetail);
        } catch (Exception e) {
            return Result.fail("500", "查询品牌详情失败: " + e.getMessage());
        }
    }

    /**
     * 基于销量生成评分
     * @param sales 销量
     * @return 评分 (4.0-5.0)
     */
    private double generateRating(Integer sales) {
        if (sales == null || sales == 0) return 4.0;
        // 销量越高评分越高，但控制在4.0-5.0范围内
        double rating = 4.0 + (sales % 10) * 0.1;
        return Math.round(rating * 10.0) / 10.0; // 保留一位小数
    }

    @GetMapping("/getAllProducts")
    public Result<List<Shoes>>getAllProducts(){
        List<Shoes>shoesList=shoesService.getAllShoes();
        if (shoesList != null)
        {
            return Result.success(shoesList);
        }
        else {
            return Result.fail("501","数据获取失败！");
        }
    }
    //修改鞋状态
    @PostMapping("/updateShoeSdelete")
    public Result<String>updataShoesIsdelete(Integer sid){
        Shoes shoes=shoesService.queryById(sid);
        System.out.println(shoes.getSdelete());
        if (shoes.getSdelete()==1) {
            shoes.setSdelete(0);
            shoesService.update(shoes);
            return Result.success("修改成功！");
        }else {
            shoes.setSdelete(1);
            shoesService.update(shoes);
            return Result.success("修改成功！");
        }
    }
    @DeleteMapping("/delete")
    public Result<String>deleteBySid(Integer sid){
        Shoes shoes=shoesService.queryById(sid);
        if (shoes == null)
        {
            return Result.fail("207","删除失败");
        }else {
            shoesService.deleteById(sid);
            return Result.success("删除成功！！");
        }
    }
    @PostMapping("/add")
    public  Result<String>add(@RequestBody Shoes shoes){
        Shoes shoes1=shoesService.findBySnum(shoes.getSnum());
        shoes.setSpubtime(new Date());
        if (!shoes.equals(shoes1))
        {
            shoesService.insert(shoes);
            return Result.success("添加成功");
        }else {
            return Result.fail("208","添加失败");
        }
    }
    @PostMapping("/updateShoesInfo")
    public Result<String>updateShoesInfo(@RequestBody Shoes shoes){
        Shoes shoes1=shoesService.queryById(shoes.getSid());
        if (shoes1 == null)
        {
            return Result.fail("209","修改失败");
        }else {
            shoesService.update(shoes);
            return Result.success("修改成功");
        }
    }
}